//app.js
var moment = require('./utils/moment.min.js');
App({
  onLaunch: function() {
    this.globalData.token = wx.getStorageSync('token');
    wx.setStorageSync('opencityid', null);
    wx.setStorageSync('opencityname', null);
    wx.setStorageSync('openareaid', null);
    wx.setStorageSync('openareaname', null); // 清空筛选医生进来读取的上次缓存
    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        if (res.code) {
          var that = this;
          var code = res.code;
          var tokened = wx.getStorageSync('token');
          wx.request({
            url: that.globalData.baseUrl + 'doctor/wx/getOpenId',
            data: {
              'code': code
            },
            header: {
              'sign': that.globalData.sign,
              'token': tokened,
              'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
            },
            method: 'POST',
            success: function(t) {
              console.log("登陆成功", t);
              that.globalData.token = t.header.token;
              wx.setStorageSync("openid", t.data.data[0].openId);
              wx.setStorageSync("token", that.globalData.token);
              that.loadings();
            }
          })
        }
      }
    })
  },
  loadings: function() {
    const that = this;
    var userInfo = wx.getStorageSync("userInfo");
    var roleType = wx.getStorageSync("roleType");
    console.log('userInfo:', userInfo);
    console.log('roleType:', roleType);
    if (userInfo == '') {
      wx.redirectTo({
        url: '../shouquan/shouquan',
      })
      return false;
    }
    if (roleType == '') {
      wx.redirectTo({
        url: '../xz/xz',
      })
      return false;
    }
    var token = that.globalData.token;
    var auditState = wx.getStorageSync('auditState');
    var userid = wx.getStorageSync('userid');
    console.log('是否在线token', token);
    console.log('是否用户端医生端roleType', roleType);
    console.log('是否过审auditState', auditState);
    console.log('userid', userid);
    if (roleType) {
      wx.request({
        url: that.globalData.baseUrl + 'doctor/member/isLogin',
        data: {},
        header: {
          'sign': that.globalData.sign,
          'token': that.globalData.token,
          'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
        },
        method: 'POST',
        success(res) {
          console.log('会员和医生是否在线1在2不在isLogin:', res.data.data[0].isLogin)
          wx.setStorageSync('isLogin', res.data.data[0].isLogin)
          if (res.data.data[0].isLogin == 1) {
            if (roleType == 1) {
              //求美者
              wx.switchTab({
                url: '/pages/index/index',
              })
            } else {
              if (auditState == 2) {
                //审核通过
                wx.redirectTo({
                  url: '/pages/doctor-index/doctor-index',
                })
                // wx.redirectTo({
                //   url: '/pages/index/index',
                // })
                // wx.reLaunch({
                  // url: '/pages/doctor-authentication-1/doctor-authentication-1',
                  // url: '/pages/doctor-authentication-2/doctor-authentication-2',                
                // })
              } else if (auditState == 3) {
                //未通过
                wx.reLaunch({
                  url: '/pages/doctor-authentication-1/doctor-authentication-1',
                })
              } else {
                //待审核          
                wx.reLaunch({
                  url: '/pages/doctor-login/doctor-login',
                })
              }
            }
          } else {
            if (roleType == 1) {
              wx.switchTab({
                url: '/pages/index/index',
              })
            } else {
              if (auditState == 2) {
                //审核通过
                wx.reLaunch({
                  url: '/pages/doctor-login/doctor-login',
                })
              } else if (auditState == 3) {
                //未通过
                wx.reLaunch({
                  url: '/pages/doctor-authentication-1/doctor-authentication-1',
                })
              } else {
                //待审核   
                wx.reLaunch({
                  url: '/pages/doctor-login/doctor-login',
                })
              }
            }
          }
        }
      })
    }
  },
  //多张图片上传
  uploadimg: function(data) {
    var that = this,
      i = data.i ? data.i : 0, //当前上传的哪张图片
      success = data.success ? data.success : 0, //上传成功的个数
      fail = data.fail ? data.fail : 0; //上传失败的个数
    wx.uploadFile({
      url: data.url,
      filePath: data.path[i],
      name: 'file', //这里根据自己的实际情况改
      formData: null, //这里是上传图片时一起上传的数据
      success: (resp) => {
        success++; //图片上传成功，图片上传成功的变量+1
        console.log(resp)
        console.log(i);
        //这里可能有BUG，失败也会执行这里,所以这里应该是后台返回过来的状态码为成功时，这里的success才+1
      },
      fail: (res) => {
        fail++; //图片上传失败，图片上传失败的变量+1
        console.log('fail:' + i + "fail:" + fail);
      },
      complete: () => {
        console.log(i);
        i++; //这个图片执行完上传后，开始上传下一张
        if (i == data.path.length) { //当图片传完时，停止调用          
          console.log('执行完毕');
          console.log('成功：' + success + " 失败：" + fail);
        } else { //若图片还没有传完，则继续调用函数
          console.log(i);
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.uploadimg(data);
        }
      }
    })
  },

  globalData: {
    token: '',
    sign: "testsign",
    apppid: "wx945bedf330bd40a4",
    appsecret: "e48775c614909d91e3ec29fe006c0e57",
    baseUrl: "https://tyc-bj.cn/yc/api/",
    staticimgUrl: "https://tyc-bj.cn/yc/api/attach/images/",
    imgUrl: "https://tyc-bj.cn/yc/api/attach/",    // 请求接口图片、视频路径
    verify: "123321",
    provinceid: 1,
    cityid: 2,
    provinceid: 1,
    provincename: '北京市',
    cityname: '北京城区',
    onetypegoodslist: [], // 一级实物商品类型列表
    onetypeservicelist: [], // 一级服务产品类型列表
    multiChoiceAnswerNow: [],
    consigneeid: '',
    consigneename: '',
    consigneephone: '',
    consigneeaddress: '',
    route1: [], //日记本图片返回路径
    route2: [], //日记本图片返回路径
    route3: [], //日记本图片返回路径
    // headportrait: "servicegood/2018/12/thumbnail_54329f0e0ccc4444909cb45dcdf4ea5b.png",
    headportrait: "images/img_touxiang_yonghuduan.png",
  },
  // fail 方法封装
  requestFail: function(res) {
    app.showModal('网络错误，请稍后再试');
  },
  /**
   * loading加载
   */
  showLoading: function() {
    wx.showLoading({
      title: '加载中...',
      mask: true
    });
  },
  /**
   * 提示消息
   */
  showModal: function(content) {
    // 显示模态弹窗
    wx.showModal({
      title: '提示消息',
      content: content,
      showCancel: false
    });
  },
  /**
   * 网络数据请求功能
   */
  request: function(param) {
    const that = this;
    const path = param.url ? param.url : '';
    let url = this.globalData.baseUrl + param.url;
    let data = param.data || {};
    wx.request({
      url: url,
      data: data,
      header: {
        'sign': that.globalData.sign,
        'token': that.globalData.token,
        'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
      },
      method: param.method || 'POST',
      dataType: 'json',
      success: function(res) {
        if (res.data.status_code == 200) {
          typeof param.success(res.data);
        } else if (res.data.status_code == 500001) {
          //跳转到登入界面
          wx.reLaunch({
            url: '/pages/user-login/user-login'
          })
        } else {
          typeof param.fail(res.data);
        }
      },
      fail: function(err) {
        console.log(err)
      }
    })
  },
  /**
   * 字段验证
   */
  validate: function(value, type, pattern) {
    // 非空
    if (type === 'required') {
      return !!value;
    }

    // 手机号
    if (type === 'phone') {
      return /^1\d{10}$/.test(value);
    }
    
    // 数字加字母
    if (type === 'alphanumeric') {
      return /^[A-Za-z0-9]+$/.test(value);
    }

    // 数字
    if (type === 'number') {
      return /^\d+(\.\d+)?$/.test(value);
    }
  },
  /**
   * 时间戳转日期格式（YYYY-MM-dd HH:mm:ss）
   */
  timeData(inputTime) {
    return moment(inputTime).format('YYYY-MM-DD');
  }
})